﻿using CrawlerFramework.Translator;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Text;
using System.Web;

namespace CrawlerFramework.Translator
{
    public class GoogleTranslateService : ITranslateService
    {
        private const string TranslateUrl = "http://translate.google.com/translate_a/t?client=j&text={0}&hl=en&sl={1}&tl={2}";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourceLanguage">iso code of the source language</param>
        /// <param name="targetLanguage">iso code of the target language</param>
        public GoogleTranslateService(string sourceLanguage, string targetLanguage)
        {
            this.SourceLanguage = sourceLanguage;
            this.TargetLanguage = targetLanguage;
        }

        public GoogleTranslateService()
        {
        }

        /// <summary>
        /// Get/set the iso code of the source language
        /// </summary>
        public string SourceLanguage
        {
            get;
            set;
        }

        /// <summary>
        /// Get/set the iso code of the target language
        /// </summary>
        public string TargetLanguage
        {
            get;
            set;
        }

        /// <summary>
        /// Translate the input text from the source language to the target language
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string Translate(string text)
        {
            if (string.IsNullOrEmpty(SourceLanguage) || string.IsNullOrEmpty(TargetLanguage))
                throw new InvalidOperationException("The source and target language must not be empty");

            if (string.IsNullOrEmpty(text))
                throw new ArgumentNullException("The text to translate must not be empty");

            var uri = string.Format(TranslateUrl, HttpUtility.UrlEncode(text), SourceLanguage, TargetLanguage);

            try
            {
                var web = new WebClient();

                // MUST add a known browser user agent or else response encoding doen't return UTF-8 (WTF Google?)
                web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
                web.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

                web.Encoding = Encoding.UTF8;
                var data = web.DownloadString(uri);

                var builder = new StringBuilder();
                var jObject = (JObject)JsonConvert.DeserializeObject(data);
                var sentences = (JArray)jObject["sentences"];
                foreach (var sentence in sentences)
                {
                    var trans = sentence["trans"];
                    builder.Append(trans.Value<string>());
                }

                return builder.ToString();
            }
            catch { }

            return text;
        }
    }
}